import React, { useState, useEffect } from 'react';
import { FaCheck, FaXmark, FaTriangleExclamation, FaCircleInfo } from 'react-icons/fa6';
import styles from './Message.module.css';

const Message = ({ 
  message, 
  type = 'info', 
  duration = 3000, 
  onClose,
  position = 'top-center' 
}) => {
  const [isVisible, setIsVisible] = useState(true);
  const [isLeaving, setIsLeaving] = useState(false);

  useEffect(() => {
    if (duration > 0) {
      const timer = setTimeout(() => {
        handleClose();
      }, duration);

      return () => clearTimeout(timer);
    }
  }, [duration]);

  const handleClose = () => {
    setIsLeaving(true);
    setTimeout(() => {
      setIsVisible(false);
      if (onClose) {
        onClose();
      }
    }, 200); // 等待动画完成
  };

  if (!isVisible) return null;

  const getIcon = () => {
    switch (type) {
      case 'success':
        return <FaCheck />;
      case 'error':
        return <FaXmark />;
      case 'warning':
        return <FaTriangleExclamation />;
      case 'info':
      default:
        return <FaCircleInfo />;
    }
  };

  return (
    <div 
      className={`${styles.message} ${styles[type]} ${styles[position]} ${
        isLeaving ? styles.leaving : styles.entering
      }`}
    >
      <div className={styles.messageContent}>
        <div className={styles.messageIcon}>
          {getIcon()}
        </div>
        <div className={styles.messageText}>
          {message}
        </div>
        <button 
          className={styles.closeButton}
          onClick={handleClose}
          title="关闭"
        >
          <FaXmark />
        </button>
      </div>
    </div>
  );
};

// Message 容器组件，用于管理多个消息
export const MessageContainer = ({ messages = [], onRemoveMessage }) => {
  return (
    <div className={styles.messageContainer}>
      {messages.map((msg) => (
        <Message
          key={msg.id}
          {...msg}
          onClose={() => onRemoveMessage && onRemoveMessage(msg.id)}
        />
      ))}
    </div>
  );
};

export default Message;
